package com.android.sunflower.logic

import android.annotation.SuppressLint
import android.app.*
import android.content.Intent
import android.os.Build
import android.os.IBinder
import android.os.Looper
import android.os.Message
import android.util.Log
import androidx.annotation.RequiresApi
import com.android.sunflower.R
import com.android.sunflower.logic.room.entities.Flower
import com.android.sunflower.ui.MainActivity
import com.android.sunflower.utils.ThreadPool
import java.util.*

class NotifyWaterService : Service() {

    companion object{
        private const val ONE_DAY_TIME:Long=1000*60*60*24
    }
    override fun onBind(intent: Intent): IBinder {
        TODO("Return the communication channel to the service.")
    }

    override fun onCreate() {
        super.onCreate()
    }

    @RequiresApi(Build.VERSION_CODES.O)
    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        val builder=Notification.Builder(MainActivity.runningInstance,"FOREGROUND_SERVICE")
        builder.apply {
            setSmallIcon(R.mipmap.ic_launcher_round)
            setContentTitle("SunFlower")
            setContentText("提醒浇水小助手")
        }
        val notification=builder.build()
        val manager=applicationContext.getSystemService(NOTIFICATION_SERVICE) as NotificationManager
        val channel=NotificationChannel("FOREGROUND_SERVICE","FOREGROUND_SERVICE",NotificationManager.IMPORTANCE_DEFAULT)
        manager.createNotificationChannel(channel)
        startForeground(1,notification)
        timedTask(ONE_DAY_TIME)
        return super.onStartCommand(intent, flags, startId)
    }

    override fun onDestroy() {
        //重启服务
        /*val intent= Intent(MainActivity.runningInstance, NotifyWaterService::class.java)
        MainActivity.runningInstance?.startService(intent)*/

        super.onDestroy()
    }

    //定时发送通知
    private fun timedTask(time:Long){
        val task=object :Runnable{
            override fun run() {
                Looper.prepare()
                while(true){
                    try{
                        val pls=Repository.selectAllPlatedF()
                        val fls= mutableListOf<Flower>()
                        for(pl in pls){
                            fls.addAll(Repository.selectFlowerByName(pl.plantName!!))
                        }
                        for(i in pls.indices){
                            val daysToWater=fls[i].waterPeriod!!-(Date().date-pls[i].waterTime?.date!!)
                            if(daysToWater<=0){
                                //Log.d("NotifyWaterService","")
                                val msg=Message().apply {
                                    what=MainActivity.NOTIFY_WATER
                                }
                                MainActivity.handler?.sendMessage(msg)
                                break
                            }
                        }
                        Thread.sleep(time)
                    }catch (e:InterruptedException){
                        MainActivity.handler?.looper?.quitSafely()
                        Log.e("NotifyWaterService", e.message!!)
                    }
                }
            }
        }
        ThreadPool.exec.execute(task)
    }
}